/**
 * Module dependencies.
 */
var mongoose = require('mongoose')
	, crypto = require('crypto')
	, Schema = mongoose.Schema

/**
 * Post Schema
 */

var PostSchema = new Schema({
  title: { type: String, default: '' },
  content: { type: String, default: '' },
  tags: [],
  user: {type: Schema.ObjectId, ref: 'User'},
  avatar: {type: String, default: '' },
  pv: { type: Number, default: 0 },
  reprint_info: {},
  createdAt: { type: Date, default: Date.now }
})


/**
 * Methods
 */

PostSchema.methods = {
  /**
   * Encrypt password
   *
   * @param {String} password
   * @return {String}
   * @api public
   */
   encryptPassword: function(password){
   		if (!password) return '';
   		var encrypred;
   		try {
   			encrypred = crypto.createHash('md5').update(password).digest('hex');
   			return encrypred;
   		} catch(err){
   			return '';
   		}
   }

}

/**
 * Statics
 */

PostSchema.statics = {

  /**
   * Find article by id
   *
   * @param {ObjectId} id
   * @param {Function} cb
   * @api private
   */

  load: function (id, cb) {
    this.findOne({ _id : id })
      //.populate('user', 'name email username')
      //.populate('comments.user')
      .exec(cb)
  },
  loadByOp: function (op, cb) {
    this.findOne(op)
      .populate('user')
      //.populate('comments.user')
      .exec(cb)
  },
  /**
   * List articles
   *
   * @param {Object} options
   * @param {Function} cb
   * @api private
   */

  list: function (options, cb) {
    var criteria = options.criteria || {}

    this.find(criteria)
      .populate('user')
      .sort({'createdAt': -1}) // sort by date
      .limit(options.perPage)
      .skip(options.perPage * options.page)
      .exec(cb)
  },
  listByOp: function (options, cb) {

    this.find(options)
      .populate('user')
      .sort({'createdAt': -1}) // sort by date
      .exec(cb)
  }

}

mongoose.model('Post', PostSchema)